<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends CF_Controller
{
	public function __construct()
	{
		parent::__construct();
		
		$this->load->library('Form_validation');
		
		$this->load->helper('form');
	}
	
	public function index()
	{
		$this->login();
	}
	//第三方连接
	public function api_connect(){
		$this->load->library('connector');
		$vendor = $this->uri->segment(3);
		!$vendor && redirect('', 'location');
		$this->connector->connect($vendor);
	}

	public function login()
	{
		$data['error_info'] = '';
		if ( ! $this->user_login->is_logged_in())
		{
			// 配置默认不显示验证码
			$data['show_captcha'] = FALSE;
				
			// 如果登录尝试超过最大尝试配置 显示验证码
			if ($this->user_login->is_max_login_attempts_exceeded())
			{
				$data['show_captcha'] = TRUE;
			}
					
			$this->load->view('auth/login_form', $data);
		}
		else
		{
			$this->user_center($this->user_login->get_user_id());
		}
	}
	
	public function register()
	{
		$data['error_info'] = '';
		if ( ! $this->user_login->is_logged_in() AND $this->user_login->allow_registration)
		{
			$this->load->view('auth/register_form', $data);

		}
		elseif ( ! $this->user_login->allow_registration)
		{
			$data['error_info'] = '注册已被禁用。';
			$this->load->view('auth/register_form', $data);
		}
		else
		{
			$this->user_center($this->user_login->get_user_id());
		}
	}

	public function logout()
	{
		$this->user_login->logout();
		redirect('', 'location');
	}

	public function user_center($uid = '', $menu_type = '', $page = '1')
	{
		$this->load->model('caipu_mdl');
		$this->load->model('user/user_like', 'ulike');
		$this->load->model('user/user_caidan', 'ucaidan');
		$this->load->model('user/user_guanzhu', 'uguanzhu');
		$this->load->model('user/users', 'users');

		$uid ? $uid : $this->user_login->get_user_id();

		$query = $this->users->get_user_by_id($uid);

		if ($query->num_rows() != 1) show_404();

		$user_info = $query->row_array();

		
		//统计
		$data['user_caipu_num'] = 0; //$this->Caipu_mdl->get_caipu_list(NULL, NULL, $uid)->num_rows();
		$data['user_guanzhu_num'] = 0; //count($this->uguanzhu->get_user_by_uid($uid));
		$data['user_fensi_num'] = 0;

		$data['uid'] = $uid;
		$data['menu_type'] = $menu_type;
		$data['userinfo'] = $user_info;
		$data['username'] = $user_info['username'];
		$data['headicon'] = $this->user_login->get_avatar_dir($uid);
		$data['skilled'] = $this->user_login->get_user_info($uid,'skilled');

		switch($menu_type){
			case 'recipe':
				$page = max(1, intval($page));
				$limit = 12; //每页显示数
				$offset = ($page - 1) * $limit;
				$data_count = 1000;

				$caipu_array = $this->caipu_mdl->get(array('authorid'=>intval($uid)), $offset, $limit)->result_array();
				$rows_array = array();
				foreach ($caipu_array as $value) 
				{
					$value['coverImage'] = server_img($value['coverImage']);
					$rows_array[] = $value;
				}
				$data['user_caipu'] = $rows_array;

				$this->load->library('pagination');
				$config['base_url'] = site_url('user/user_center/'.$uid.'/recipe');
				$config['total_rows'] = $data_count;
				$config['per_page'] = $limit; 
				$config['uri_segment'] = 4;
				$this->pagination->initialize($config); 

				$this->load->view('auth/user_recipe', $data);
				break;
			case 'caidan':
				$this->load->model('Caidan_mdl');
				$this->load->helper('text');
				$page = max(1, intval($page));
				$limit = 12; //每页显示数
				$offset = ($page - 1) * $limit;
				$data_count = 1000;

				$ucaidan_array = $this->ucaidan->get_caidan_uid($uid, $offset, $limit)->result_array();
				$ucaidan_rows_array = array();
				foreach ($ucaidan_array as $value) 
				{
					$value['location'] = server_img($value['location']);
					$ucaidan_rows_array[] = $value;
				}
				$data['user_caidan'] = $ucaidan_rows_array;

				$this->load->library('pagination');
				$config['base_url'] = site_url('user/user_center/'.$uid.'/caidan');
				$config['total_rows'] = $data_count;
				$config['per_page'] = $limit; 
				$config['uri_segment'] = 4;
				$this->pagination->initialize($config); 
				$this->load->view('auth/user_caidan', $data);
				break;
			case 'fav':
				$this->load->model('user/user_favorite', 'ufavorite');
				$page = max(1, intval($page));
				$limit = 12; //每页显示数
				$offset = ($page - 1) * $limit;
				$data_count = 1000;
				$data['like_shicai'] = $this->ulike->get_like_by_uid($uid)->result_array();
				$data['user_caipu'] = $this->ufavorite->get_caipu_fav_by_user($uid, $offset, $limit)->result_array();
				$this->load->library('pagination');
				$config['base_url'] = site_url('user/user_center/'.$uid.'/fav');
				$config['total_rows'] = $data_count;
				$config['per_page'] = $limit; 
				$config['uri_segment'] = 4;
				$this->pagination->initialize($config); 

				$this->load->view('auth/user_fav', $data);
				break;
			case 'fav_cd':
				$this->load->model('user/user_favorite', 'ufavorite');
				$this->load->model('Caidan_mdl');
				$this->load->helper('text');
				$page = max(1, intval($page));
				$limit = 12; //每页显示数
				$offset = ($page - 1) * $limit;
				$data_count = 1000;
				$data['user_fav_caidan'] = $this->ufavorite->get_caidan_fav_by_user($uid, $offset, $limit)->result_array();

				$this->load->library('pagination');
				$config['base_url'] = site_url('user/user_center/'.$uid.'/caidan');
				$config['total_rows'] = $data_count;
				$config['per_page'] = $limit; 
				$config['uri_segment'] = 4;
				$this->pagination->initialize($config); 
				$this->load->view('auth/user_fav_caidan', $data);
				break;
			default:
				$caipu_array = $this->caipu_mdl->get(array('authorid'=>intval($uid)), 0, 6)->result_array();
				$rows_array = array();
				foreach ($caipu_array as $value) 
				{
					$value['coverImage'] = server_img($value['coverImage']);
					$rows_array[] = $value;
				}
				$data['user_caipu'] = $rows_array;
				$data['user_caidan'] = $this->ucaidan->get_caidan_uid($uid)->result_array();
				$data['user_guanzhu'] = $this->uguanzhu->get_user_by_uid($uid);
				$this->load->view('auth/user_center', $data);
				break;
		}
	}

	public function activate()
	{
		$username = urldecode($this->uri->segment(3));
		$key = $this->uri->segment(4);
		$data['title'] = '用户激活';

		if ($this->user_login->activate($username, $key)) 
		{
			$data['message'] = '您的帐户已成功激活。';
			$data['message2'] = anchor(site_url('user/login'), '登录');
			$this->load->view('auth/complete', $data);
		}
		else
		{
			$data['message'] = '对不起，系统错误，请稍后再试';
			$data['message2'] = anchor(site_url(), '返回首页');
			$this->load->view('auth/complete', $data);
		}
	}
	
	public function forgot_password()
	{
		$val = $this->form_validation;
		
		$val->set_rules('email', 'Username or Email address', 'trim|required|xss_clean');

		if ($val->run() AND $this->user_login->forgot_password($val->set_value('email')))
		{
			$data['title'] = '重置密码邮件已发送';
			$data['message'] = '邮件已发送！请重新设定密码:)';
			$data['message2'] = '若未收到，请点击 <a href="'.site_url('user/forgot_password').'">重新发送邮件</a>';
			$this->load->view('auth/complete', $data);
		}
		else
		{
			$this->load->view('auth/forgot_password_form');
		}
	}
	
	public function reset_password()
	{
		$username = $this->uri->segment(3);
		$key = $this->uri->segment(4);

		// 重置密码
		$data['title'] = '重置密码';
		if ($this->user_login->reset_password($username, $key))
		{
			$data['message'] = '您的临时密码已生效！, 请尽快更改密码！';
			$data['message2'] = anchor(site_url('/user/login/'), '登录');
			$this->load->view('auth/complete', $data);
		}
		else
		{
			$data['message'] = '操作失败！你填写的邮箱或密钥有误。请检查您的电子邮件，按照指示操作。';
			$data['message2'] = anchor(site_url(), '返回首页');
			$this->load->view('auth/complete', $data);
		}
	}

	//修改资料
	public function profile()
	{
		$data['message'] = '';

		if ($this->user_login->is_logged_in())
		{
			$uid = $this->user_login->get_user_id();
			$data['email'] = $this->user_login->get_user_info($uid,'email');
			$data['username'] = $this->user_login->get_user_info($uid,'username');
			$data['sex'] = $this->user_login->get_user_info($uid,'sex');
			$data['birthday'] = explode('-',$this->user_login->get_user_info($uid,'birthday'));
			$data['flavor'] = $this->user_login->get_user_info($uid,'flavor');
			$data['skilled'] = $this->user_login->get_user_info($uid,'skilled');

			$val = $this->form_validation;
			
			$val->set_rules('username', 'username', 'trim|xss_clean');
			$val->set_rules('sex', 'sex', 'trim|xss_clean');
			$val->set_rules('birthyear', 'birthyear', 'trim|xss_clean');
			$val->set_rules('birthmonth', 'birthmonth', 'trim|xss_clean');
			$val->set_rules('birthday', 'birthday', 'trim|xss_clean');
			$val->set_rules('province', 'province', 'trim|xss_clean');
			$val->set_rules('city', 'city', 'trim|xss_clean');
			$val->set_rules('taste', 'taste', 'trim|xss_clean');
			$val->set_rules('signature', 'signature', 'trim|xss_clean');
			
			if ($val->run() )
			{
				$birthday = $val->set_value('birthyear').'-'.$val->set_value('birthmonth').'-'.$val->set_value('birthday');
				$this->user_login->change_profile($val->set_value('username'), $val->set_value('sex'), $birthday, $val->set_value('taste'), $val->set_value('signature'));
				$data['message'] = '修改成功';
				redirect('user/profile', 'location');
			}
		}
		else
		{
			redirect('user/login', 'location');
			exit;
		}

		$this->load->view('auth/profile', $data);
	}

	//修改头像
	public function portrait($action = '')
	{
		$user_pic = '';
		$uid = $this->user_login->get_user_id();

		if ($this->user_login->is_logged_in())
		{
			$avatar_info = $this->user_login->get_avatar_info($uid);

			if ($action)
			{
				$rs = array();
				switch($action){
					case 'uploadavatar':
						$input = file_get_contents('php://input');
						$data = explode('--------------------', $input);

						$file_name_s=$avatar_info[0].'/'.$avatar_info[1].'_thumb.jpg';
						$file_name=$avatar_info[0].'/'.$avatar_info[1].'.jpg';

						@file_put_contents($file_name_s, $data[0]);
						@file_put_contents($file_name, $data[1]);

						$rs['status'] = 1;
						break;
					default:
						$rs['status'] = -1;
				}
				print json_encode($rs);
			}

		}
		else
		{
			redirect('user/login', 'location');
			exit;
		}

		$data['user_pic']  = $this->user_login->get_avatar_dir($uid);
		$this->load->view('auth/portrait', $data);
	}

	//前台提交网站内容
	public function create($info = 'caipu')
	{
		if ($this->user_login->is_logged_in())
		{
			$this->load->model('Caipu_mdl');
			$val = $this->form_validation;
			$val->set_rules('cook_name', 'Cook_name', 'trim|required|xss_clean');
			$val->set_rules('cook_deal', 'Cook_deal', 'trim|xss_clean');
			$val->set_rules('costtime', 'Costtime', 'trim|xss_clean');
			$val->set_rules('coverImageId', 'CoverImageId', 'trim|required|xss_clean');
			$val->set_rules('coverImageUrl', 'CoverImageUrl', 'trim|required|xss_clean');
			$val->set_rules('cookStory', 'CookStory', 'trim|xss_clean');
			$val->set_rules('materials[str]', 'Materials_str', 'trim|required|xss_clean');
			$val->set_rules('materials[int]', 'Materials_int', 'trim|xss_clean');
			$val->set_rules('setpInfos[]', 'SetpInfos[]', 'trim|required|xss_clean');
			$val->set_rules('setpImageIds[]', 'SetpImageIds[]', 'trim|xss_clean');
			$val->set_rules('setpImages[]', 'SetpImages[]', 'trim|xss_clean');
			$val->set_rules('cooktips', 'Cooktips', 'trim|xss_clean');
			$val->set_rules('cooktag', 'Cooktag', 'trim|xss_clean');

			if ($val->run() )
			{
				//格式化用料materials数组
				$materials = $this->input->post('materials');

				$mater = '';
				for($i=0;$i<count($materials['str']);$i++) 
				{ 
					($i > 0) && $mater.='|';
					$mater.=$materials['str'][$i].'，'.$materials['int'][$i];

				}

				//格式化步骤setpInfos数组
				$setpInfos = $this->input->post('setpInfos');
				$setpInfo = '';
				for($i=0;$i<count($setpInfos);$i++) 
				{
					($i > 0) && $setpInfo.='|';
					$setpInfo.=$setpInfos[$i];
				}

				//格式化步骤图id数组
				$setpImageIds = array_filter($this->input->post('setpImageIds'));
				$setpImageId = implode(',', $setpImageIds);

				$arr = array(
					'author' => $this->user_login->get_username(),
					'authorid' => $this->user_login->get_user_id(),
					'title' => $val->set_value('cook_name'),
					'costtime' => $val->set_value('costtime'),
					'deal' => $val->set_value('cook_deal'),
					'infos' => $val->set_value('cookStory'),
					'coverImage' => $val->set_value('coverImageUrl'),
					'materials' => $mater,
					'setpInfos' => $setpInfo,
					'tips' => $val->set_value('cooktips'),
					'class_name' => $val->set_value('cooktag'),
					'time' => time(),
					'views' => 0,
					'status' => 0
				);
				$insert_id = $this->Caipu_mdl->caipu_insert($arr);
				$this->load->model('Attach_mdl');
				$this->Attach_mdl->caipu_attach_update(array('caipu_id' => $insert_id), $val->set_value('coverImageId') );
				if(!empty($setpImageId)) $this->Attach_mdl->caipu_attach_update(array('caipu_id' => $insert_id), $setpImageId);

				redirect('recipe/'.$insert_id, 'location');
			}
			else
			{
				$data[] = '';
				$this->load->view('auth/create_caipu', $data);
			}
		}
		else
		{
			redirect('user/login', 'location');
		}
	}

	public function change_password()
	{
		if ($this->user_login->is_logged_in())
		{			
			$val = $this->form_validation;

			$val->set_rules('old_password', 'Old Password', 'trim|required|xss_clean|min_length[4]|max_length[20]');
			$val->set_rules('new_password', 'New Password', 'trim|required|xss_clean|min_length[4]|max_length[20]|matches[confirm_new_password]');
			$val->set_rules('confirm_new_password', 'Confirm new Password', 'trim|required|xss_clean');
			
			if ($val->run() AND $this->user_login->change_password($val->set_value('old_password'), $val->set_value('new_password')))
			{
				$data['auth_message'] = '修改成功.';
			}
			else
			{
				if($this->input->post())
				{
					$data['auth_message'] = '错误.';
				}
				else
				{
					$data['auth_message'] = '';
				}
			}

			$this->load->view('auth/change_password', $data);
		}
		else
		{
			redirect('user/login', 'location');
		}
	}	
	
	public function cancel_account()
	{
		if ($this->user_login->is_logged_in())
		{			
			$val = $this->form_validation;
			
			$val->set_rules('password', 'Password', "trim|required|xss_clean");
			
			if ($val->run() AND $this->user_login->cancel_account($val->set_value('password')))
			{
				redirect('', 'location');
			}
			else
			{
				$this->load->view($this->user_login->cancel_account_view);
			}
		}
		else
		{
			redirect('user/login', 'location');
		}
	}

	// 权限查看范例 无用
	public function custom_permissions()
	{
		if ($this->user_login->is_logged_in())
		{
			echo 'My role: '.$this->user_login->get_role_name().'<br/>';
			echo 'My permission: <br/>';
			
			if ($this->user_login->get_permission_value('edit') != NULL AND $this->user_login->get_permission_value('edit'))
			{
				echo 'Edit is allowed';
			}
			else
			{
				echo 'Edit is not allowed';
			}
			
			echo '<br/>';
			
			if ($this->user_login->get_permission_value('delete') != NULL AND $this->user_login->get_permission_value('delete'))
			{
				echo 'Delete is allowed';
			}
			else
			{
				echo 'Delete is not allowed';
			}
		}
	}
}

/* End of file user.php */
/* Location: ./application/controllers/user.php */